package com.xms.queryview.service;

import com.xms.queryview.core.component.CellDescriptor;
import com.xms.queryview.core.component.GridDescriptor;
import com.xms.queryview.entity.QueryView;
import com.xms.schema.entity.Attribute;
import com.xms.schema.entity.Entity;
import com.xms.utils.StringUtil;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * GridService
 * </p>
 *
 * @author migo
 * @since 2021/9/21
 */
@Service
public class GridService implements IGridService {

    @Override
    public GridDescriptor Build(QueryView view, List<Entity> entities, List<Attribute> attributes) {
        GridBuilder gridBuilder = new GridBuilder(view);
        GridDescriptor grid = gridBuilder.grid;
        int i = 0;
        for (CellDescriptor cell : grid.Rows.get(0).Cells)
        {
            if (StringUtil.isEmpty(cell.Label))
            {
                if (cell.EntityName.equalsIgnoreCase(view.getEntityname()))//主实体
                {
                    Attribute attr = attributes.stream().filter(x -> x.getName().equalsIgnoreCase(cell.Name) && x.getEntityname().equalsIgnoreCase(view.getEntityname())).findFirst().orElse(null);
                    if (attr != null)
                    {
                        grid.Rows.get(0).Cells.get(i).Label = attr.getLocalizedname();
                    }
                }
                else //关联实体
                {
                    //当列为关联实体字段时，列名加上关联实体名
                    String[] temp = StringUtil.splitSafe(cell.Name, ".");
                    if (temp.length > 1)
                    {
                        Attribute attr = attributes.stream().filter(x -> x.getName().equalsIgnoreCase(temp[1]) && x.getEntityname().equalsIgnoreCase(cell.EntityName)).findFirst().orElse(null);
                        if (attr != null)
                        {
                            grid.Rows.get(0).Cells.get(i).Label = attr.getLocalizedname() + "(" + attr.getEntityname() + ")";
                        }
                    }
                }
            }
            i++;
        }

        return grid;
    }
}
